package com.example.apidocserver.infrastructure.aop;

import com.example.apidocserver.domain.user.event.UserInfoEventService;
import com.example.apidocserver.infrastructure.base.BaseEntity;
import com.example.apidocserver.infrastructure.util.MyDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * 权限切面
 *
 * @author xyqlg
 */
@Aspect
@Component
@Slf4j
public class QueryAop {
    @Resource
    private UserInfoEventService userInfoEventService;

    @Pointcut("@annotation(com.example.apidocserver.infrastructure.aop.QueryAnno)")
    public void action() {
    }

    @Around("action()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        setUserAndTime(proceed);
        return proceed;
    }

    private void setUserAndTime(Object proceed) {
        if (proceed instanceof Collection) {
            for (Object obj : (Collection) proceed) {
                setUserAndTimeDo(obj);
            }

        } else {
            setUserAndTimeDo(proceed);
        }
    }

    private void setUserAndTimeDo(Object methodArg) {
        if (methodArg instanceof BaseEntity) {
            BaseEntity entity = ((BaseEntity) methodArg);
            entity.setCreateTimeStr(MyDateUtils.toShowDataStr(entity.getCreateTime()))
                    .setUpdateTimeStr(MyDateUtils.toShowDataStr(entity.getUpdateTime()))
                    .setCreatorStr(userInfoEventService.getNickNameById(entity.getCreator()))
                    .setUpdaterStr(userInfoEventService.getNickNameById(entity.getUpdater()));
        }
    }
}